package commons.baseServlet;

import com.alibaba.fastjson.JSON;
import commons.r.R;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * servlet.baseServlet
 * User: 邱
 * Date: 2024/11/27 18:12
 * Description:
 * Version: V1.0
 */
public class BaseServlet extends HttpServlet {
    /**
     * 获取请求的接口名
     * @param url
     * @return
     */
    public String getSuffixURL(String url){
        int index = url.lastIndexOf("/");
        return index == -1 ? null : url.substring(index + 1);
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        //获取请求路径
        String requestURI = request.getRequestURI();
        //获取需要请求的接口名（方法名）
        String methodName = getSuffixURL(requestURI);
        //使用获取的方法名
        if (methodName != null){
            //使用反射获取方法
            Class c = this.getClass();//对象已存在  获取该对象
            try {
                //获取该方法                                     方法都需要请求request类型的参数
                Method method = c.getDeclaredMethod(methodName, HttpServletRequest.class);
                //调用该方法
                Object returnValue = method.invoke(this, request);
                //判断该方法返回的值的类型  以进行响应操作
                if (returnValue instanceof String){//一个路径
                    //重定向和转发
                    String url = returnValue.toString();
                    if (url.startsWith("f:")){
                        //转发  并去掉 f:
                        request.getRequestDispatcher(url.replace("f:", "")).forward(request, response);
                    }else {
                        //重定向
                        response.sendRedirect(url);
                    }
                } else if (returnValue instanceof R) {//结果集类型
                    String jsonString = JSON.toJSONString(returnValue);
                    PrintWriter writer = response.getWriter();
                    writer.write(jsonString);
                    writer.close();
                } else if (returnValue instanceof File) {//文件类型  需要下载这个文件  响应给浏览器
                    File file = (File) returnValue;
                    //获取文件名
                    String fileName = file.getName();
                    //设置响应格式    传输流
                    response.setContentType("application/octet-stream");
                    //设置响应头
                    response.setHeader("Content-disposition", "attachment; filename=" + fileName);
                    //创建输入流
                    BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
                    //创建输出流
                    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
                    //边读边写
                    int i;
                    while ((i = bufferedInputStream.read()) != -1){
                        bufferedOutputStream.write(i);
                    }
                    bufferedOutputStream.flush();
                    //关流
                    bufferedOutputStream.close();
                    bufferedInputStream.close();
                } else if (returnValue instanceof HSSFWorkbook) {//Excel类型  需要下载该Excel  响应给浏览器
                    //设置文件名
                    String fileName = System.currentTimeMillis() + ".xls";
                    //设置响应头
                    response.setHeader("Content-disposition", "attachment; filename=" + fileName);
                    //设置响应格式
                    response.setContentType("application/vnd.ms-excel");
                    //响应给浏览器
                    HSSFWorkbook hssfWorkbook = (HSSFWorkbook) returnValue;
                    hssfWorkbook.write(response.getOutputStream());
                }

            } catch (NoSuchMethodException e) {
                e.printStackTrace();
                System.out.println("这个方法不存在！！！");
            } catch (InvocationTargetException | IllegalAccessException e) {
                e.printStackTrace();
                System.out.println("没权限调用该方法！！！");
            }

        }
    }
}
